package com.allwees.bs.c.module.ops.controller;

import com.allwees.bs.c.module.base.controller.BaseController;
import com.allwees.bs.c.module.ops.service.UserCouponService;
import com.allwees.bs.c.module.ops.vo.FreeGiftGetInfo;
import com.allwees.bs.c.module.ops.vo.UserCouponVo;
import com.allwees.bs.c.module.product.VoConvertor;
import com.allwees.bs.c.module.product.dto.ProductDetailsDTO;
import com.allwees.bs.c.module.product.entity.FreeGiftRecord;
import com.allwees.bs.c.module.product.entity.ProductEntity;
import com.allwees.bs.c.module.product.service.FreeGiftRecordService;
import com.allwees.bs.c.module.product.service.ProductService;
import com.allwees.bs.c.module.user.entity.UserCouponEntity;
import com.allwees.bs.core.model.product.entity.ProductModel;
import com.allwees.bs.core.modelbase.page.PageParams;
import com.allwees.bs.core.modelbase.page.PaginateDTO;
import com.allwees.bs.core.modelbase.vo.R;
import com.allwees.core.common.util.DateUtil;
import com.allwees.support.marketing.aop.ResetPrice;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 营销相关
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/marketing")
public class MarketingController extends BaseController implements VoConvertor {

    @Resource
    private UserCouponService userCouponService;

    @Resource
    private ProductService productService;

    @Resource
    private FreeGiftRecordService freeGiftRecordService;

    /**
     * 用户是否领取注册优惠券和Free Gift
     *
     * @return
     */
    @GetMapping("/gift/info")
    public R freeGiftGetInfo() {
        String userUuid = super.getUserUuid();
        Assert.isTrue(StringUtils.isNotBlank(userUuid), "Please Login First~");
        FreeGiftGetInfo info = new FreeGiftGetInfo();
        boolean applied = freeGiftRecordService.hasApplied(userUuid);
        info.setApplied(applied);
        UserCouponEntity registeredCoupon = userCouponService.getRegisteredCoupon(userUuid);
        if (registeredCoupon != null) {
            info.setCoupon(new UserCouponVo(registeredCoupon));
        }
        info.setCompleted(applied && registeredCoupon != null);
        return R.ok(info);
    }

    /**
     * 新用户领取注册优惠券
     *
     * @return
     */
    @PostMapping("/coupon/get")
    public R getNewRegisterCoupon() {
        String userUuid = super.getUserUuid();
        Assert.isTrue(StringUtils.isNotBlank(userUuid), "Please Login First~");
        //因为前端交互的缺陷，这里先领取再从数据库查询返回
        UserCouponEntity coupon = userCouponService.newRegisteredUserGet(userUuid);
        if (coupon == null) {
            coupon = userCouponService.getRegisteredCoupon(userUuid);
        }
        return R.ok(coupon);
    }

    /**
     * free gift for new users
     *
     * @param pageParams
     * @return
     */
    @ResetPrice
    @GetMapping("/gifts")
    public R freeGifts(@Validated PageParams pageParams) {
        PaginateDTO<ProductDetailsDTO> dto = productService.findMarketingProducts(ProductModel.MARKETING_TYPE_2, pageParams);
        String userUuid = super.getUserUuid();
        if (StringUtils.isNotBlank(userUuid)) {
            List<ProductEntity> products = productService.freeGiftsInOnesCart(userUuid);
            if (CollectionUtils.isNotEmpty(products)) {
                dto.setFreeGiftUuid(products.get(0).getUuid());
                if (products.size() > 1) {
                    log.error("===> user cart has more than one free gifts.userUuid:{}", userUuid);
                }
            } else {
                FreeGiftRecord record = freeGiftRecordService.getById(userUuid);
                if (record != null) {
                    dto.setFreeGiftUuid(record.getProductUuid());
                }
            }
        }
        return R.ok(convert(dto));
    }

    /**
     * flash sales
     *
     * @param pageParams
     * @return
     */
    @ResetPrice
    @GetMapping("/flash")
    public R flashSales(@Validated PageParams pageParams, @RequestParam(name = "ask", required = false) String ask) {
        Date marketingDate = new Date();
        if (StringUtils.equalsIgnoreCase("tomorrow", ask)) {
            marketingDate = DateUtil.addDays(marketingDate, 1);
        }
        int marketingDay = Integer.parseInt(DateUtil.formatDate(marketingDate, "yyyyMMdd"));
        PaginateDTO<ProductDetailsDTO> dto = productService.flashProducts(pageParams, marketingDay);
        dto.setRemainMillis(DateUtil.todayRemainsMills());
        return R.ok(convert(dto));
    }

    /**
     * 网红商品
     *
     * @param pageParams
     * @return
     */
    @ResetPrice
    @GetMapping("/influs")
    public R influ(@Validated PageParams pageParams) {
        return R.ok(convert(productService.findMarketingProducts(ProductModel.MARKETING_TYPE_1, pageParams)));
    }

    /**
     * 获取加价以后价格为$5以下的商品
     *
     * @param pageParams
     * @return
     */
    @ResetPrice
    @GetMapping("/below5")
    public R below5(@Validated PageParams pageParams) {
        return R.ok(convert(productService.below5Products(pageParams)));
    }
}
